﻿using NPOI.HSSF.UserModel;
using SF.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.finance
{
    public partial class business_settlement : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string action = string.Empty;
        protected string keywords = string.Empty;
        protected int state = -1;

        protected string settleNum = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.state = Request["state"] == null ? -1 : int.Parse(Request["state"]);
            this.keywords = DTRequest.GetQueryString("keywords");
            this.action = DTRequest.GetQueryString("action");
            this.settleNum = DTRequest.GetQueryString("settleNum");

            if (action == "GetBusinessUserNames") 
            {
                GetBusinessUserNames();
            }
            if (this.action == "export")
            {
                ExportData();
            }


            if (string.IsNullOrEmpty(this.settleNum) == false)
            {
                BLL.sf_finance_settlement bll = new BLL.sf_finance_settlement();
                Model.sf_finance_settlement model = bll.GetModel(this.settleNum);
                this.lbsettlement_num.Text = this.settleNum;
                this.lboperator.Text = model.user_name;
                this.lbcreate_time.Text = model.create_time.ToString();
                this.lbtotal.Text = model.total_amount.ToString();
                this.lbreceived.Text = model.received.ToString();
                this.lbnot_received.Text = model.not_received.ToString();
            } 

            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("app_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind(" sf_finance_settlement_num = '" + settleNum + "' and  id>0" + CombSqlTxt(this.keywords), "id desc");
            }
        }

        #region 导出数据

        private void ExportData()
        {
            string strWhere = " id>0" + CombSqlTxt(this.keywords) + " order by id desc";
            BLL.sf_business_settlement bll = new BLL.sf_business_settlement();
            System.Data.DataSet dsList = bll.GetList(strWhere);

            Hashtable hsColumns = new Hashtable();
            hsColumns.Add("sf_finance_settlement_num", "结算单编号");
            hsColumns.Add("busnieseNum", "商户编号");
            hsColumns.Add("businessName", "商户名称");
            hsColumns.Add("user_name", "经手人");
            hsColumns.Add("total_amount", "合计");
            hsColumns.Add("state", "状态");
            hsColumns.Add("状态", "状态");
            hsColumns.Add("create_time", "生成时间");

            //1、移除不必要的字段
            for (int i = dsList.Tables[0].Columns.Count - 1; i >= 0; i--) 
            {
                string column_name = dsList.Tables[0].Columns[i].ColumnName;
                if (hsColumns.Contains(column_name) == false) 
                {
                    dsList.Tables[0].Columns.Remove(column_name);
                }
            }
            dsList.Tables[0].Columns.Add("状态");
            foreach (System.Data.DataRow r in dsList.Tables[0].Rows)
            {
                r["状态"] = r["state"].ToString() == "0" ? "未完成收费" : "已完成收费";
            }
            dsList.Tables[0].Columns.Remove("state");

            //2、调整列名称
            foreach (System.Data.DataColumn col in dsList.Tables[0].Columns)
            {
                col.ColumnName = hsColumns[col.ColumnName].ToString();
            }

            dsList.Tables[0].Columns.RemoveAt(0);
            dsList.Tables[0].TableName = "商户结算单列表";
            HSSFWorkbook workbook = NPOIExcelHelper.GridToExcelByNPOI(dsList);

            DownLoad(workbook, "商户结算单列表");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="hssfWorkbook">excel工作簿</param>
        /// <param name="fileName">文件名</param>
        private void DownLoad(HSSFWorkbook hssfWorkbook, string fileName)
        {
            using (MemoryStream memoryStram = new MemoryStream())
            {
                //把工作簿写入到内存流中
                hssfWorkbook.Write(memoryStram);
                //设置输出编码格式
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                //设置输出流
                Response.ContentType = "application/octet-stream";
                //防止中文乱码
                fileName = HttpUtility.UrlEncode(fileName);
                //设置输出文件名
                Response.AppendHeader("Content-Disposition", "filename=" + fileName + ".xls");
                //输出
                Response.BinaryWrite(memoryStram.GetBuffer());
            }
        } 

        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }

        #endregion

        private void GetBusinessUserNames()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "No-Cache");

            string businessNums = DTRequest.GetQueryString("businessNums");
            string[] arr_nums = businessNums.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string query_businessNums = string.Empty;
            foreach (string num in arr_nums) 
            {
                query_businessNums += "'" + num + "',";
            }

            if (query_businessNums.Length > 0) 
            {
                query_businessNums = query_businessNums.Remove(query_businessNums.Length - 1 , 1);
            }

            string userNames = string.Empty;
            string userRealNames = string.Empty;
            BLL.manager bll = new BLL.manager();
            System.Data.DataSet dsManagers = bll.GetList(" busnieseNum in (" + query_businessNums + ")");
            foreach (System.Data.DataRow r in dsManagers.Tables[0].Rows) 
            {
                userNames += r["user_name"].ToString()+",";
                userRealNames += r["real_name"].ToString()+",";
            }

            Response.Clear();
            Response.Write("{userNames:'" + userNames + "',userRealNames:'" + userRealNames + "'}");
            Response.End();
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.ddlStatus.SelectedValue = this.state.ToString();

            this.page = DTRequest.GetQueryInt("page", 1);
            txtKeywords.Text = this.keywords;
            BLL.sf_business_settlement bll = new BLL.sf_business_settlement();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = string.Format("business_settlement.aspx?state={0}&keywords={1}&page={2}&settleNum={3}", ddlStatus.SelectedValue, this.keywords, "__id__",this.settleNum);
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (busnieseNum like '%" + _keywords + "%' or businessName like '%" + _keywords + "%' or settlement_times like '%" + _keywords + "%' or user_name like '%" + _keywords + "%')");
            }

            if (state > -1)
            {
                strTemp.Append(" and state = " + state);
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("finance_business_page_size", "DTcmsPage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string pageUrl = string.Format("business_settlement.aspx?state={0}&keywords={1}&settleNum={2}", ddlStatus.SelectedValue, this.txtKeywords.Text,this.settleNum);
            Response.Redirect(pageUrl);
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("finance_business_page_size", "DTcmsPage", _pagesize.ToString(), 14400);
                }
            }

            string pageUrl = string.Format("business_settlement.aspx?state={0}&keywords={1}&settleNum={2}", ddlStatus.SelectedValue, this.keywords,this.settleNum);
            Response.Redirect(pageUrl);
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            string url = string.Format("business_settlement.aspx?state={0}&keywords={1}&settleNum={2}", ddlStatus.SelectedValue, this.keywords,this.settleNum);
            Response.Redirect(url);
        }
    }
}